package tr.edu.ozyegin.ccrg.raid.reader;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Observable;

import tr.edu.ozyegin.ccrg.raid.network.Client;
import tr.edu.ozyegin.ccrg.raid.progressbar.ProgressBar;

public class FileReader extends Observable implements Runnable {
	private ArrayList<Boolean> doneList = null;
	private short ID = 0;
	private long from = 0;
	private long size = 0;
	private String fileName = null;
	private Client client = null;
	private final int ChunkSize = 500000;
	private ProgressBar progress = null;
	
	public FileReader(String fileName, ArrayList<Boolean> doneList, short ID, long from, long size,Client client, ProgressBar progress){
		this.progress = progress;
		this.doneList = doneList;
		this.ID = ID;
		this.from = from;
		this.size = size;
		this.fileName = fileName;
		this.client = client;
	}
	private synchronized void setDone(){
		this.doneList.set(this.ID, new Boolean(true));
		boolean flag = true;
		for(int i = 0; i< this.doneList.size(); i++){
			Boolean b = this.doneList.get(i);
			if(b == false)flag = false;
		}
		if(flag){
			this.setChanged();
			this.notifyObservers();
		}
	}
	
	@Override
	public void run() {
		try {
			FileInputStream fs = new FileInputStream(this.fileName);
			fs.skip(this.from);
			BufferedInputStream bs = new BufferedInputStream(fs);
			byte[] buffer = null;
			this.client.Write(new Long(this.size));
			if(this.size < ChunkSize){
				buffer = new byte[(int)this.size];
				bs.read(buffer);
				this.client.WriteBytes(buffer, false);
				this.progress.updateProgress(buffer.length);
			}
			else{
				int iteration = (int)(this.size / ChunkSize);
				int toWrite = ChunkSize;
				buffer = new byte[ChunkSize];
				for(int i = 0 ; i < iteration ;i++){
					if(i == iteration - 1){
						toWrite = (int)(this.size - ((iteration - 1)*ChunkSize));
						buffer = new byte[toWrite];
					}
					bs.read(buffer);
					this.client.WriteBytes(buffer, false);
					
					this.progress.updateProgress(buffer.length);
				}
			}
			this.setDone();
			bs.close();
			fs.close();
			/*
			fs.read(this.bufferList.get(this.ID), 0, (int) this.size);
			this.client.Write(new Long(this.size));
			this.client.WriteBytes(this.bufferList.get(this.ID),false);
			this.setDone();
			fs.close();
			*/
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}
